const express = require("express");
const rolesRouter = express.Router();
const DB = require("./../db/config");

module.exports = rolesRouter;

/**
 * 获取所有角色
 * 按角色模糊查询
 */
rolesRouter.route("/roles/getAll").get(function (req, res) {
  console.log("请求角色", req.query);
  let { searchText } = req.query;
  let sql = "";
  let params = [];
  if (searchText !== undefined) {
    sql = "select * from roles where rname like ?;";
    params.push("%" + searchText + "%");
  } else {
    sql = "select * from roles;";
  }

  let cb = (err, data) => {
    if (!err) {
      res.json({ code: 0, data, msg: "查询角色成功" });
    } else {
      res.json({ code: 0, msg: "查询角色失败" });
    }
  };
  DB.connect(sql, params, cb);
});

/**
 * 添加角色
 * @param {String} rname
 * @param {String} rdes
 */
rolesRouter.route("/roles/addRole").post(function (req, res) {
  let { rname, rdes } = req.body;
  let sql = "insert into roles values(null,?,?,default);";
  let params = [rname, rdes];
  let cb = (err, data) => {
    if (err === null) {
      res.json({
        code: 0,
        msg: "添加角色成功",
        data: [],
      });
    } else {
      res.json({
        code: 40002,
        msg: "添加角色失败",
        data: [],
      });
    }
  };
  DB.connect(sql, params, cb);
});

/**
 * 修改角色状态
 * @param rid {Number} 角色ID
 * @param rstate {Number} 角色状态
 *
 */
rolesRouter.route("/roles/modifyAccessState").post((req, res) => {
  let { rid, rstate } = req.body;
  let sql = "update roles set rstate = ? where rid = ?;";
  let params = [rstate, rid];
  let cb = (err, data) => {
    if (err === null) {
      res.json({
        code: 0,
        msg: "修改状态成功。",
        data: [],
      });
    } else {
      res.json({
        code: 40002,
        msg: "修改状态失败。",
        data: [],
      });
    }
  };
  DB.connect(sql, params, cb);
});
/**
 * 获取一个角色绑定的用户。
 * @param rid  {Number} 角色ID
 */
rolesRouter.route("/roles/getUsersForOneRole").get((req, res) => {
  let rid = req.query.rid;
  let sql =
    "select * from roles  as r join userroletable as urt  on r.rid =urt.rid join users as u on u.uid = urt.uid where urt.rid = ?;";
  let params = [rid];
  let cb = (err, data) => {
    console.log(err);
    console.log(data);
    if (err === null) {
      res.json({ code: 0, msg: "查询成功。", data });
    } else {
      res.json({ code: 4002, msg: "查询失败。", data });
    }
  };
  DB.connect(sql, params, cb);
});

/**
 * 给角色添加用户
 * @param selectRoleId {Number} 角色ID
 * @param userSelectedId {Array} 用户数组
 */
rolesRouter.route("/roles/addUserToRole").post((req, res) => {
  let { selectRoleId, userSelectedId } = req.body;
  console.log(req.body);
  new Promise((resolve, reject) => {
    let delSql = "delete from userroletable where rid = ?;";
    let delParam = [selectRoleId];
    let cb = (err, data) => {
      if (!err) {
        resolve("删除一个角色的所有用户成功");
      } else {
        reject("删除一个角色的所有用户失败");
      }
    };
    DB.connect(delSql, delParam, cb);
  })
    .then((data) => {
      // console.log("userSelectedId",userSelectedId);
      return new Promise((resolve, reject) => {
        let params = [];
        let temp = [];
        // console.log("给角色设置:",userSelectedId.length);

        if (userSelectedId === undefined) {
          // console.log("!");
          resolve("取消角色批量设置用户成功。");
        } else {
          // console.log("!!");
          userSelectedId.forEach((el) => {
            temp.push("(?,?)");
            params.push(el, selectRoleId);
          });
          let sql = "insert into userroletable (uid,rid) values";
          sql = sql + temp.join(",");
          //  console.log(sql);
          //  console.log(params);
          let cb = (err, data) => {
            console.log(err);
            if (err === null) {
              resolve("给角色设置用户成功。");
            } else {
              reject("给角色设置用户失败。");
            }
          };
          DB.connect(sql, params, cb);
        }
      });
    })
    .then((data) => {
      res.json({ code: 0, msg: data, data: [] });
    })
    .catch((err) => {
      console.log(err);
      res.json({ code: 4002, msg: err, data: [] });
    });
});

/**
 * 删除一个角色
 */

rolesRouter.route("/roles/delRole").post((req, res) => {
  let rid = req.body.rid;
  let sql = "delete from roles where rid = ?;";
  let param = [rid];
  let cb = (err, data) => {
    if (!err) {
      res.json({ code: 0, msg: "删除角色成功", data: [] });
    } else {
      res.json({ code: 4002, msg: "删除角色成功", data: [] });
    }
  };
  DB.connect(sql, param, cb);
});

/**
 * 获取一个角色的所有已关联的权限
 */
rolesRouter.route("/roles/getAccessForOneRole")
.get((req, res)=>{
  let rid = req.query.rid;
  let param = [rid];
  let sql = 'select * from rolepermissinstable where rid = ?;';
  let cb = (err, data)=>{
    if (!err) {
      res.json({code: 0, msg:'获取一个角色的所有已关联的权限成功',data})
    } else {
      res.json({code: 4002, msg:'获取一个角色的所有已关联的权限失败',data})
      
    }
  };
  DB.connect(sql, param, cb)
});

/**
 * 给一个角色，添加权限
 * @param {Number} selectRoleId ,角色ID，required
 * @param {Array} accessSelectedId, 权限ID，
 */

rolesRouter.route("/api/addAccessForRole")
.post((req, res)=>{
  let { selectRoleId, accessSelectedId } = req.body;
  console.log(req.body);
  new Promise((resolve, reject) => {
    let delSql = "delete from rolepermissinstable where rid = ?;";
    let delParam = [selectRoleId];
    let cb = (err, data) => {
      if (!err) {
        resolve("删除一个角色的所有权限成功");
      } else {
        reject("删除一个角色的所有权限失败");
      }
    };
    DB.connect(delSql, delParam, cb);
  })
    .then((data) => {
      // console.log("userSelectedId",userSelectedId);
      return new Promise((resolve, reject) => {
        let params = [];
        let temp = [];
        // console.log("给角色设置:",userSelectedId.length);

        if (accessSelectedId === undefined) {
          // console.log("!");
          resolve("取消角色批量设置权限成功。");
        } else {
          // console.log("!!");
          accessSelectedId.forEach((el) => {
            temp.push("(?,?)");
            params.push(el, selectRoleId);
          });
          let sql = "insert into rolepermissinstable (pid,rid) values";
          sql = sql + temp.join(",");
          //  console.log(sql);
          //  console.log(params);
          let cb = (err, data) => {
            console.log(err);
            if (err === null) {
              resolve("给角色批量设置权限成功。");
            } else {
              reject("给角色批量设置权限失败。");
            }
          };
          DB.connect(sql, params, cb);
        }
      });
    })
    .then((data) => {
      res.json({ code: 0, msg: data, data: [] });
    })
    .catch((err) => {
      console.log(err);
      res.json({ code: 4002, msg: err, data: [] });
    });
})